import React, { Component } from 'react';
import { Dispatch } from 'redux';

import _ from 'lodash';

import { inputNumber, addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  Table,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import styles from '../index.less';
import { statusList, columns } from '../constant';

const { Item } = Form;
const { Option } = Select;

interface userSurveyProps extends FormComponentProps {
 dispatch: Dispatch<any>;
 loading:boolean;
 tabIndex:string;
 userInfo:any;
 userList:any;
 searchValues:any;
 pageIndex:any;
 pageSize:any;
 changeQuery:(obj:Object) => void
}

class UserSurveyElem extends Component<userSurveyProps> {
  componentDidMount() {
    this.setFieldsValue();
    this.fetchList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const {
      searchValues, pageIndex, pageSize,
    } = this.props;
    if (!_.isEqual(searchValues, prevProps.searchValues)
      || pageIndex !== prevProps.pageIndex
      || pageSize !== prevProps.pageSize
    ) {
      this.setFieldsValue();
      this.fetchList();
    }
  }

   // 设置表单值
   setFieldsValue = () => {
     const {
       searchValues: { wechatPhone = '', status = '0' },
     } = this.props;

     const { form: { setFieldsValue } } = this.props;
     setFieldsValue({ wechatPhone, status });
   }

  // 获取用户概况列表
  fetchList = () => {
    const {
      dispatch, searchValues, searchValues: { status }, pageIndex, pageSize,
    } = this.props;

    dispatch({
      type: 'tencentConfig/fetchUserList',
      payload: {
        pageSize,
        pageIndex,
        ...searchValues,
        status: status === '0' ? '' : status,
      },
    });
  }

  // 去授权
  accredit = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '公众号配置',
      url: '/tencent/impower/config?tab=3',
    });
  }

  // 监听用户手机号输入
  changePhone = (e:any) => {
    const value = inputNumber(e);

    const { form: { setFieldsValue } } = this.props;
    setTimeout(() => {
      setFieldsValue({ wechatPhone: value });
    }, 0);
  }

  // 查询
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const {
      form: { validateFields }, pageSize,
    } = this.props;
    validateFields((errors:any, fieldsValue:any) => {
      if (errors) return;

      this.commonQuery(fieldsValue, 1, pageSize);
    });
  }

  // 重置
  handleFormReset = () => {
    const {
      form: { resetFields }, pageSize,
    } = this.props;
    resetFields();

    this.commonQuery({}, 1, pageSize);
  }

  // 切换页码
  onSelectChange = (page: number, psize: number | undefined) => {
    const { searchValues } = this.props;

    this.commonQuery(searchValues, page, psize);
  }

  commonQuery = (searchValues:any, pageIndex:any, pageSize:any) => {
    const { changeQuery, tabIndex } = this.props;

    const query = {
      pageSize,
      pageIndex,
      tab: tabIndex,
      ...searchValues,
    };

    changeQuery(query);
  }

  render() {
    const {
      userInfo,
      userList,
      pageIndex,
      pageSize,
      loading,
      form: { getFieldDecorator },
    } = this.props;

    const pagination = userList
      ? {
        total: userList.count,
        pageSize: Number(pageSize),
        current: Number(pageIndex),
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${userList.count}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    const columnsList = [{
      title: '微信头像',
      dataIndex: 'headImg',
      render: (text:any) => (
        <img src={text} alt="" style={{ width: '25px' }} />
      ),
    }, ...columns];

    return (
      <>
        <Card bordered={false} className="noMarginLeft">
          <p>新关注人数、累计关注人数根据昨日数据来计算，总用户数根据当前数据计算，两者不一致。</p>
          <Row gutter={12} style={{ margin: '16px 0' }}>
            <Col md={8} sm={24}>
              <Card size="small" className={styles.newlyIncreased}>
                <p className={styles.title}>新关注人数</p>
                <p className={styles.number}>{userInfo.newNumber || 0}</p>
              </Card>
            </Col>

            <Col md={8} sm={24}>
              <Card size="small" className={styles.accumulative}>
                <p className={styles.title}>累计关注用户</p>
                <p className={styles.number}>{userInfo.focusNumber || 0}</p>
              </Card>

            </Col>
            <Col md={8} sm={24}>
              <Card size="small" className={styles.mailServer}>
                <p className={styles.title}>总用户数</p>
                <p className={styles.number}>{userInfo.totalNumber || 0 }</p>
              </Card>
            </Col>
          </Row>
        </Card>

        <Card bordered={false} className="noMarginLeft">
          <Form onSubmit={this.handleSearch} className="tableListForm">
            <Row gutter={12}>
              <Col md={7} sm={24}>
                <Item label="用户手机号" colon={false}>
                  {getFieldDecorator('phone')(
                    <Input
                      allowClear
                      maxLength={11}
                      autoComplete="off"
                      placeholder="请输入用户手机号"
                      onChange={this.changePhone}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="状态" colon={false}>
                  {getFieldDecorator('status', {
                    initialValue: '0',
                  })(
                    <Select placeholder="请选择">
                      {statusList.map((item: any) => (
                        <Option
                          key={item.id}
                          value={String(item.id)}
                        >
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={11} sm={24}>
                <div className="flexFeView" style={{ margin: '0 0 20px 0' }}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton marginL16 smallButton"
                    onClick={this.handleFormReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
          <Table
            rowKey="id"
            loading={loading}
            columns={columnsList}
            dataSource={userList.list}
            pagination={pagination}
          />
        </Card>
      </>
    );
  }
}

export default Form.create<userSurveyProps>()(UserSurveyElem);
